home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / cpp_libs / answrbok / 8_2.lha / 8_2 / 8_2a.c next >
C/C++ Source or Header  |  1993-08-08  |  1KB  |  74 lines

  1. * Copyright (c) 1990 by AT&T Bell Telephone Laboratories, Incorporated. */
  2. * The C++ Answer Book */
  3. * Tony Hansen */
  4. * All rights reserved. */
  5. / Exercise 8.2
  6. truct name_and_address
  7.  
  8.    char **name;
  9.    int len;
  10.  
  11.    name_and_address()
  12.    {
  13. name = new char*[1];
  14. name[0] = 0;
  15. len = 1;
  16.    }
  17.  
  18.    // construct an address using
  19.    // another as its initializer
  20.    name_and_address(name_and_address &na)
  21.    {
  22. // init name and pass the buck to op=
  23. name = 0;
  24. *this = na;
  25.    }
  26.  
  27.    // A helper function to remove the strings.
  28.    // This is used by assignment and input.
  29.    void deallocate_name();
  30.  
  31.    // assign one address to another
  32.    name_and_address& operator=(name_and_address &na)
  33.    {
  34. // delete any strings already there
  35.        deallocate_name();
  36.  
  37. // allocate and copy the strings
  38. name = new char*[na.len];
  39. for (char **tmpname = name, **tmpnaname = na.name;
  40.      *tmpnaname; tmpname++, tmpnaname++)
  41.     {
  42.     *tmpname = new char[strlen(*tmpnaname) + 1];
  43.     strcpy(*tmpname, *tmpnaname);
  44.     }
  45.  
  46. *tmpname = 0;
  47. len = na.len;
  48. return *this;
  49.    }
  50.  
  51.    // remove the parts of an address
  52.    ~name_and_address()
  53.    {
  54. deallocate_name();
  55.    }
  56.  
  57.    // input and output
  58.    friend istream& operator>>
  59. (istream&, name_and_address&);
  60.    friend ostream& operator<<
  61. (ostream&, name_and_address&);
  62. ;
  63.  
  64. oid name_and_address::deallocate_name()
  65.  
  66.    if (name)
  67. {
  68. for (char **svname = name; *svname; )
  69.     delete *svname++;
  70. delete name;
  71. name = 0;
  72. }
  73.  
  74.